const {Recommend} = require('../../models/Recommend');

module.exports = async (req, res) => {
    let skipNum = parseInt(req.query.skipNum) || 0;
    var recoms = [];

//查询用户信息的规则
let opt1 = [{$lookup:{
            from: "users",
            localField: "user_id",
            foreignField: "user_id",
            as: "userInfo"}},
    {$project:{
            "userInfo.user_id":1,
            "userInfo.nickname":1,
            "userInfo.avatar":1,
            "userInfo.sex":1}},
    {$skip:skipNum},   
    {$limit:5},  //限制查询条数
]
//根据Art_No联合查询商品信息
let opt2 = [{$lookup:{
            from: "commodities",
            localField: "Art_No",
            foreignField: "Art_No",
            as: "commodity"}},
    { $project:{
            "commodity.Art_No":1,
            "commodity.customPrice":1,
            "commodity.appearance":1,
            "commodity.freight":1}},
    {$skip:skipNum},
    {$limit:5},
];
//根据ISBN联合查询图书信息
let opt3 = [{ $lookup:{
            from: "books",
            localField: "ISBN",
            foreignField: "ISBN",
            as: "book" }},
    { $project:{
            "book.ISBN":1,
            "book.title":1,
            "book.author": 1,
            "book.publisher":1,
            "book.img":1}},
    {$skip:skipNum},
    {$limit:5},
]
    //根据user_id联合查询用户信息集合中的对应用户信息
    Recommend.aggregate(opt1, (err, data) => {
        if (err) {
            res.status(500).send({errCode:"1",msg:"服务器内部错误"})
        } else {
            for(let i=0;i<data.length;i++){
                //将查询结果存入recoms变量
                recoms.push(data[i].userInfo[0])
            }
            //根据Art_No联合查询商品信息
            Recommend.aggregate(opt2, (err, data) => {
                if (err) {
                    res.status(500).send({errCode:"1",msg:"服务器内部错误"})
                } else {
                    for(let i=0;i<data.length;i++){
                        Object.assign(recoms[i], data[i].commodity[0])
                    }
                    //根据ISBN联合查询图书信息
                    Recommend.aggregate(opt3, (err, data) => {
                        if (err) {
                            res.status(500).send({errCode:"1",msg:"服务器内部错误"})
                        } else {
                            for(let i=0;i<data.length;i++){
                                Object.assign(recoms[i], data[i].book[0])
                            }
                           res.send({errCode:"0",msg:"请求成功",data:{recommends:recoms}}); 
                        }
                    });
                }
            });
        }
    });
}